<template>
    <div class="common-layout">
        <el-container class="index-con">
            <el-aside class="index-aside" style="width: 240px;">
                <el-menu default-active="/exam" class="side-menu" router :background-color="isNightMode ? '#1a1a1a' : '#f5f7fa'"
                    :text-color="isNightMode ? '#e0e0e0' : '#2c3e50'" :active-text-color="'#409EFF'" style="height: 100%;">
                    <div class="system-title">
                        <span class="title-text">NERV</span>
                        <div class="title-decoration"></div>
                    </div>
                    <el-menu-item class="create-exam-item">
                        <el-button type="primary" class="create-exam-btn" @click="goToCreateExam">
                            <el-icon><Plus /></el-icon>
                            创建考试
                        </el-button>
                    </el-menu-item>
                    <el-menu-item index="/exam" class="menu-item">
                        <el-icon><Expand /></el-icon>
                        <span>考试管理</span>
                    </el-menu-item>
                    <el-menu-item index="/ex/mark-exam" class="menu-item">
                        <el-icon><School /></el-icon>
                        <span>人工评卷</span>
                    </el-menu-item>
                    <el-sub-menu  class="menu-item">
                        <template #title>
                            <el-icon><DataAnalysis /></el-icon>
                            <span>分析</span>
                        </template>
                        <el-menu-item index="/ex/text-socre" class="submenu-item">
                            <el-icon><Histogram /></el-icon>
                            <span>考试成绩</span>
                        </el-menu-item>
                        <!--  -->
                
                    </el-sub-menu>
                </el-menu>
            </el-aside>
            <el-container>
                <el-header class="main-header">
                    <Header />
                </el-header>
                <el-main class="index-main">
                    <div class="search-section">
                        <el-select v-model="status" placeholder="考试状态" size="large" class="status-select" @change="handleStatusChange">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                        <el-input v-model="searchText" class="search-input" size="large" placeholder="请输入名称查询" @input="handleSearch">
                            <template #prefix>
                                <el-icon><Search /></el-icon>
                            </template>
                        </el-input>
                        <el-button type="danger" :disabled="selectedExams.length === 0" @click="handleBatchDelete">
                            批量删除
                        </el-button>
                    </div>
                    <div class="table-section">
                        <el-table 
                            :data="tableData" 
                            style="width: 100%" 
                            :border="false" 
                            class="custom-table" 
                            v-loading="loading"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" />
                            <el-table-column property="examId" label="编号" width="100" />
                            <el-table-column property="examName" label="考试名称" width="180" />
                            <el-table-column property="subject" label="科目" width="120" />
                            <el-table-column property="startTime" label="开始时间" width="180">
                                <template #default="scope">
                                    <span>{{ formatDateTime(scope.row.startTime) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column property="duration" label="考试时长(分钟)" width="120" />
                            <el-table-column property="totalScore" label="总分" width="120" />
                            <el-table-column label="状态" width="120">
                                <template #default="scope">
                                    <el-tag :type="getStatusType(scope.row.status)">
                                        {{ scope.row.status }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="300">
                                <template #default="scope">
                                    <div class="action-buttons">
                                        <el-button type="primary" link class="action-btn" @click="handleView(scope.row)">
                                            <el-icon><View /></el-icon>
                                            查看
                                        </el-button>
                                        <el-button type="primary" link class="action-btn" @click="handleEdit(scope.row)">
                                            <el-icon><Edit /></el-icon>
                                            编辑
                                        </el-button>
                                        <el-button v-if="scope.row.status === '待发布'" type="success" link class="action-btn" @click="showPublishDialog(scope.row)">
                                            <el-icon><Upload /></el-icon>
                                            发布
                                        </el-button>
                                        <el-button type="danger" link class="action-btn" @click="handleDelete(scope.row)">
                                            <el-icon><Delete /></el-icon>
                                            删除
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination-section">
                            <el-pagination
                                v-model:current-page="currentPage"
                                v-model:page-size="pageSize"
                                :page-sizes="[10, 20, 50, 100]"
                                :background="true"
                                layout="total, sizes, prev, pager, next"
                                :total="total"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                class="custom-pagination"
                            />
                        </div>
                    </div>
                </el-main>
            </el-container>
        </el-container>
        <!-- 发布考试对话框 -->
        <el-dialog
            v-model="publishDialogVisible"
            title="发布考试"
            width="500px"
        >
            <el-form :model="publishForm" label-width="120px">
                <el-form-item label="发布类型">
                    <el-radio-group v-model="publishForm.target_type" @change="handleTargetTypeChange">
                        <el-radio label="class">班级发布</el-radio>
                        <el-radio label="student">个人发布</el-radio>
                    </el-radio-group>
                </el-form-item>
                
                <el-form-item label="发布对象">
                    <el-select
                        v-model="publishForm.target_id"
                        multiple
                        :placeholder="publishForm.target_type === 'class' ? '请选择班级' : '请选择学生'"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in targetOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="publishDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlePublish">确认发布</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Histogram, School, Expand, CloseBold, FolderChecked, DataAnalysis, Plus, Search, View, Edit, Delete, Upload } from '@element-plus/icons-vue';
import { ref, watch, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import Header from '@/components/Header.vue';
import { useTheme } from '@/stores/themeStore';
import examApi from '@/api/exam';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const themeStore = useTheme();
const isNightMode = computed(() => themeStore.isNightMode);

// 状态筛选
const status = ref('');
const statusOptions = [
    { value: '', label: '所有考试' },
    { value: '待添加试题', label: '待添加试题' },
    { value: '待发布', label: '待发布' },
    { value: '待开始', label: '待开始' },
    { value: '已开始', label: '已开始' },
    { value: '已结束', label: '已结束' },
    { value: '进行中', label: '进行中' }
];

// 搜索文本
const searchText = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 表格数据
const tableData = ref([]);

// 选中的考试
const selectedExams = ref([]);

// 发布考试相关
const publishDialogVisible = ref(false);
const publishForm = ref({
    examId: null,
    target_type: 'class',
    target_id: []
});
const targetOptions = ref([]);

// 获取考试列表
const fetchExamList = async () => {
    loading.value = true;
    try {
        const response = await examApi.getExamList({
            status: status.value,
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            schoolNumber: sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')).schoolNumber : null,
            searchText: searchText.value
        });
        console.log('获取到的考试列表数据:', response);
        if (response.code === 200) {
            tableData.value = response.data;
            total.value = response.data && response.data.length > 0 ? response.data[0].total : 0;
        } else {
            ElMessage.error(response.message || '获取考试列表失败');
        }
    } catch (error) {
        console.error('获取考试列表失败:', error);
        ElMessage.error('获取考试列表失败');
    } finally {
        loading.value = false;
    }
};

// 状态变化处理
const handleStatusChange = () => {
    currentPage.value = 1;
    fetchExamList();
};

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1;
    fetchExamList();
};

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchExamList();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchExamList();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    return date.toLocaleString();
};

// 获取状态标签类型
const getStatusType = (status) => {
    const types = {
        '待添加试题': 'info',
        '待发布': 'warning',
        '待开始': 'primary',
        '已开始': 'success',
        '已结束': 'danger'
    };
    return types[status] || 'info';
};

// 查看考试详情
const handleView = (row) => {
    router.push({
        name: 'ExamDetail',
        params: { id: row.examId }
    });
};

// 编辑考试
const handleEdit = (row) => {
    router.push({
        name: 'EditExam',
        params: { id: row.examId }
    });
};

// 创建考试
const goToCreateExam = () => {
    router.push({ name: 'CreateExam' });
};

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedExams.value = selection;
};

// 处理单个删除
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这场考试吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const response = await examApi.deleteExams([row.examId]);
            if (response.code === 200) {
                ElMessage.success('删除成功');
                fetchExamList(); // 重新加载列表
            } else {
                ElMessage.error(response.message || '删除失败');
            }
        } catch (error) {
            console.error('删除考试失败:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {});
};

// 处理批量删除
const handleBatchDelete = () => {
    if (selectedExams.value.length === 0) {
        ElMessage.warning('请选择要删除的考试');
        return;
    }

    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedExams.value.length} 场考试吗？`, 
        '提示', 
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const examIds = selectedExams.value.map(exam => exam.examId);
            const response = await examApi.deleteExams(examIds);
            if (response.code === 200) {
                ElMessage.success('批量删除成功');
                fetchExamList(); // 重新加载列表
            } else {
                ElMessage.error(response.message || '批量删除失败');
            }
        } catch (error) {
            console.error('批量删除考试失败:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {});
};

// 显示发布对话框
const showPublishDialog = async (row) => {
    publishForm.value.examId = row.examId;
    publishForm.value.target_id = [];
    publishDialogVisible.value = true;
    await loadTargetOptions();
};

// 加载发布对象选项
const loadTargetOptions = async () => {
    try {
        let response;
        const userInfo = sessionStorage.getItem('userInfo');
        const schoolNumber = userInfo ? JSON.parse(userInfo).schoolNumber : null;
        
        if (!schoolNumber) {
            ElMessage.error('未获取到教师信息');
            return;
        }

        if (publishForm.value.target_type === 'class') {
            response = await examApi.getTeacherClasses(schoolNumber);
            if (response.code === 200) {
                // 使用班级的实际ID而不是名称
                targetOptions.value = response.data.map(item => ({
                    id: item.classId,  // 使用实际的班级ID
                    name: item.className
                }));
            }
        } else {
            response = await examApi.getTeacherStudents(schoolNumber);
            if (response.code === 200) {
                targetOptions.value = response.data.map(item => ({
                    id: item.schoolNumber,
                    name: `${item.name} (${item.schoolNumber}) - ${item.className}`
                }));
            }
        }
    } catch (error) {
        console.error('加载发布对象失败:', error);
        ElMessage.error('加载发布对象失败');
    }
};

// 发布类型变更处理
const handleTargetTypeChange = () => {
    publishForm.value.target_id = [];
    loadTargetOptions();
};

// 发布考试
const handlePublish = async () => {
    try {
        if (!publishForm.value.target_id || publishForm.value.target_id.length === 0) {
            ElMessage.warning('请选择发布对象');
            return;
        }

        await ElMessageBox.confirm('确定要发布该考试吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        console.log('准备发布的考试数据:',publishForm.value)
        const response = await examApi.publishExam(publishForm.value);
        if (response.code === 200) {
            ElMessage.success('考试发布成功');
            publishDialogVisible.value = false;
            fetchExamList();
        } else {
            ElMessage.error(response.message || '考试发布失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('发布考试失败:', error);
            ElMessage.error('发布考试失败');
        }
    }
};

onMounted(() => {
    themeStore.initTheme();
    fetchExamList();
});
</script>

<style scoped>
.index-con {
    width: 100vw;
    height: 100vh;
    background-color: var(--el-bg-color);
}

.index-aside {
    background-color: var(--el-menu-bg-color);
    border-right: 1px solid var(--el-border-color-lighter);
    transition: all 0.3s ease;
}

.system-title {
    padding: 20px;
    text-align: center;
    position: relative;
}

.title-text {
    font-size: 28px;
    font-weight: 600;
    background: linear-gradient(45deg, #409EFF, #36d1dc);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    display: inline-block;
    position: relative;
}

.title-decoration {
    width: 60%;
    height: 2px;
    background: linear-gradient(90deg, transparent, #409EFF, transparent);
    margin: 10px auto 0;
}

.create-exam-item {
    padding: 20px !important;
    margin: 0 !important;
    height: auto !important;
}

.create-exam-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 8px;
    background: linear-gradient(45deg, #409EFF, #36d1dc);
    border: none;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.create-exam-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.menu-item {
    margin: 4px 0;
    border-radius: 4px;
}

.submenu-item {
    padding-left: 54px !important;
}

.main-header {
    background-color: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-lighter);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.index-main {
    padding: 20px;
    background-color: var(--el-bg-color-page);
}

.search-section {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
}

.status-select,
.category-select {
    width: 160px;
}

.search-input {
    width: 300px;
}

.table-section {
    background: var(--el-bg-color);
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-table {
    margin-bottom: 20px;
}

:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: var(--el-bg-color-page);
    font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
    background-color: var(--el-bg-color-page);
}

.time-text {
    color: var(--el-text-color-secondary);
}

.action-buttons {
    display: flex;
    gap: 8px;
}

.action-btn {
    display: flex;
    align-items: center;
    gap: 4px;
}

.pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.custom-pagination {
    padding: 10px 0;
}

/* Night mode specific styles */
:deep(.night-mode) {
    .index-con {
        background-color: #1a1a1a;
    }

    .index-aside {
        background-color: #242424;
        border-color: #333;
    }

    .main-header {
        background-color: #1a1a1a;
        border-color: #333;
    }

    .table-section {
        background-color: #242424;
    }

    :deep(.el-table) {
        background-color: #242424;
        color: #e0e0e0;
    }

    :deep(.el-table th) {
        background-color: #1a1a1a;
    }

    :deep(.el-table td) {
        border-color: #333;
    }

    .time-text {
        color: #909399;
    }
}
</style>